<?php
namespace Services;
/**
 * File holds class for User data manipulation
 *
 * PHP version 5.3.5
 *
 * @category   CM
 * @package    Services
 * @subpackage -
 * @author     markus karileet <markuskarileet@hotmail.com>
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL
 * @link       -
 */
class User extends ORM {
	/**
	 * Method searches user by email or phone. When user is found, then it is
	 * returned, otherwise false
	 * @param var $email
	 * @param var $phone
	 * @return \Entities\User on success, false on error
	 */
	public function findUserByEmailOrPhone($email, $phone) {
		$dbUser = false;
		//first off try to find user by email
		if (strlen($email) > 0) {
			$user = new \Entities\User();
			$user->setEmail($email);
			$dbUser = $this->select($user);
		}
		//then try to find user by phone
		if (strlen($phone) > 0 && !$dbUser) {
			$user = new \Entities\User();
			$user->setPhone($phone);
			$dbUser = $this->select($user);
		}
		
		//when user is found, return it, otherwise false
		return $dbUser;
	}
	
	/**
	 * Method prepares data for user storing
	 * @param array $post HTML POST array
	 * @return int ID after successful insert, or 0 when problems 
	 */
	public function prepareSave($post) {
		$id = 0;
		if (isset($post['email']) || isset($post['phone'])) {
			$user = new \Entities\User();
			$user->setPhone($post['phone']);
			$user->setEmail($post['email']);
			try {
				$id = $this->insert($user);
			} catch (\Exception $e) {
				$id = 0;
				//TODO: DO not eat exception
			}
		}
		return $id;
	}
}